package cn.wolfcode.luowowo.item.service.impl;

import cn.wolfcode.luowowo.common.exception.LogicException;
import cn.wolfcode.luowowo.item.domain.Item;
import cn.wolfcode.luowowo.item.domain.UserItem;
import cn.wolfcode.luowowo.item.mapper.ItemMapper;
import cn.wolfcode.luowowo.item.mapper.UserItemMapper;
import cn.wolfcode.luowowo.item.query.ItemQuery;
import cn.wolfcode.luowowo.item.service.IUserItemService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class UserItemServiceImpl implements IUserItemService {
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private UserItemMapper userItemMapper;
    @Reference
    private IUserInfoService userInfoService;
    @Override
    public PageInfo queryForList(Long userId, ItemQuery qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<UserItem> list = userItemMapper.selectForList(userId,qo);
        return new PageInfo(list);
    }

    @Override
    public void buyItem(Long userId, Long itemId) throws LogicException {
        //如果商品剩余数为0，提示购买的商品无足够库存
        //int rest = itemMapper.queryForRest(itemId);
        Item item = itemMapper.selectByPrimaryKey(itemId);
        if(item.getRest() == 0){
            throw new LogicException("购买的商品无足够库存");
        }
        //如果用户金币数不足，提示你的金币不够
        BigDecimal score = userInfoService.queryForScore(userId);
        if(score.subtract(item.getPrice()).intValue() < 0){
            throw new LogicException("您的金币不足");
        }
        //先查询当前用户是否有购买过当前商品,如果有，直接剩余数加一即可
        UserItem userItem = userItemMapper.queryForUserIdAndItemName(userId,item.getName());
        if(userItem != null){
            userItem.setRest(userItem.getRest() + 1);
            userItem.setDate(new Date());
            userItemMapper.updateByPrimaryKey(userItem);
        }else{
            userItem = new UserItem();
            userItem.setDate(new Date());
            userItem.setImgUrl(item.getImgUrl());
            userItem.setName(item.getName());
            userItem.setUserId(userId);
            userItem.setRest(1);
            userItemMapper.insert(userItem);
        }
        //用户的金币数减去商品价格
        userInfoService.payForItem(userId,item.getPrice());
        //用户购买数量加一后，商品数量应该减一
        item.setRest(item.getRest() - 1);
        itemMapper.updateByPrimaryKey(item);
    }
}
